using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using BurnSys;
using CommonLib;

namespace TestAdbCommand
{
    public class CommandResult
    {
        public bool Success { get; set; }
        public string Result { get; set; }
    }

    public static class AdbCommandHelper
    {
        private const string DEVICE_NOT_FOUND_ERROR = "error: no devices/emulators found";
        private static Process _pingProcess;
        private static CancellationTokenSource _pingCancellationTokenSource;

        public static CommandResult ExecuteAdbCommand(string command, int type)
        {
            try
            {
                switch (type)
                {
                    case 1:
                        return ExecuteDirectCommand(command);
                    case 2:
                        return ExecuteBatchFile(command);
                    case 3:
                        return ExecuteTokenCommand();
                    case 4:
                        return ExecuteDatabaseTestCommand();
                    case 5:
                        return ExecuteUpdateSecretsCommand();
                    case 6:
                        return ExecuteViewSecretsCommand();
                    case 7:
                        return ExecuteTestUserSecretsDatabaseCommand();
                    case 8:
                        return ExecuteLongPingCommand(command);
                    default:
                        return new CommandResult { Success = false, Result = "未知的命令类型" };
                }
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"执行命令时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteDirectCommand(string command)
        {

            using (Process process = new Process())
            {
                // 如果是 adb 命令，确保 adb 在 PATH 环境变量中
                // 如果是 find 命令，直接执行（Windows 内置）
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = $"/c \"{command}\"";  // 用引号包裹命令，防止特殊字符被 cmd 解析
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                process.StartInfo.StandardErrorEncoding = Encoding.UTF8;

                StringBuilder output = new StringBuilder();
                StringBuilder error = new StringBuilder();

                process.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        output.AppendLine(e.Data);
                    }
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();


                string result = output.ToString().Trim();
                string errorResult = error.ToString().Trim();

                if (errorResult.Contains(DEVICE_NOT_FOUND_ERROR))
                {
                    return new CommandResult { Success = false, Result = "错误：未找到设备或模拟器" };
                }


                // 检查 find 命令是否报错
                if (!string.IsNullOrEmpty(errorResult))
                {
                    return new CommandResult { Success = false, Result = errorResult };
                }

                return new CommandResult { Success = true, Result = result };
            }
        }

        private static CommandResult ExecuteBatchFile(string batchFileName)
        {
            string batchFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, batchFileName);
            
            if (!File.Exists(batchFilePath))
            {
                return new CommandResult { Success = false, Result = $"找不到批处理文件：{batchFileName}" };
            }

            string str = string.Empty;
            string errMsg = string.Empty;
            using (Process process = new Process())
            {
                FileInfo fileInfo = new FileInfo(batchFileName);
                process.StartInfo.WorkingDirectory = fileInfo.Directory.FullName;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = batchFilePath;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.UseShellExecute = false;
                process.Start();
                process.WaitForExit();
                str = process.StandardOutput.ReadToEnd();
                errMsg = process.StandardError.ReadToEnd();

                if (errMsg.Contains(DEVICE_NOT_FOUND_ERROR))
                {
                    return new CommandResult { Success = false, Result = "错误：未找到设备或模拟器" };
                }

                return new CommandResult { Success = true, Result = str };
            }
        }

        private static CommandResult ExecuteTokenCommand()
        {
            try
            {
                // 执行获取token的固定函数
                string token = MachineCode.GetMachineCode();
                
                if (string.IsNullOrEmpty(token))
                {
                    return new CommandResult { Success = false, Result = "获取机器码失败" };
                }
                
                return new CommandResult { Success = true, Result = token };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"获取token时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteDatabaseTestCommand()
        {
            try
            {
                // 从配置文件中读取加密的连接字符串
                string encryptedConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"]?.ConnectionString;
                
                if (string.IsNullOrEmpty(encryptedConnectionString))
                {
                    return new CommandResult { Success = false, Result = "配置文件中未找到数据库连接字符串" };
                }
                
                if (encryptedConnectionString == "")
                {
                    return new CommandResult { Success = false, Result = "请先在配置文件中设置正确的加密连接字符串" };
                }
                
                // 使用AESEncryptHelper解密连接字符串
                string connectionString;
                try
                {
                    connectionString = AESEncryptHelper.Decrypt(encryptedConnectionString);
                }
                catch (Exception decryptEx)
                {
                    return new CommandResult { Success = false, Result = $"解密数据库连接字符串失败：{decryptEx.Message}" };
                }
                
                if (string.IsNullOrEmpty(connectionString))
                {
                    return new CommandResult { Success = false, Result = "解密后的连接字符串为空" };
                }
                
                // 测试数据库连接
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    
                    // 执行一个简单的查询来验证连接
                    using (SqlCommand command = new SqlCommand("SELECT 1", connection))
                    {
                        object result = command.ExecuteScalar();
                        if (result != null && result.ToString() == "1")
                        {
                            return new CommandResult 
                            { 
                                Success = true, 
                                Result = $"数据库连接测试成功！\n服务器：{connection.DataSource}\n数据库：{connection.Database}" 
                            };
                        }
                        else
                        {
                            return new CommandResult { Success = false, Result = "数据库连接测试失败：查询返回异常结果" };
                        }
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                return new CommandResult { Success = false, Result = $"SQL Server连接错误：{sqlEx.Message}" };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"数据库连接测试时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteUpdateSecretsCommand()
        {
            try
            {
                // 从配置文件中读取加密的连接字符串
                string encryptedConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"]?.ConnectionString;
                
                if (string.IsNullOrEmpty(encryptedConnectionString))
                {
                    return new CommandResult { Success = false, Result = "配置文件中未找到数据库连接字符串" };
                }
                
                // 构建UserSecrets路径
                string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string secretsPath = Path.Combine(userProfile, @"AppData\Roaming\Microsoft\UserSecrets\e67ad845-4b88-4662-9d66-34960dfb67d9\secrets.json");
                
                if (!File.Exists(secretsPath))
                {
                    return new CommandResult { Success = false, Result = $"找不到secrets.json文件：{secretsPath}" };
                }
                
                // 读取现有的JSON文件
                string jsonContent;
                try
                {
                    jsonContent = File.ReadAllText(secretsPath, Encoding.UTF8);
                }
                catch (Exception readEx)
                {
                    return new CommandResult { Success = false, Result = $"读取secrets.json文件失败：{readEx.Message}" };
                }
                
                // 解析JSON
                JsonDocument jsonDoc;
                try
                {
                    jsonDoc = JsonDocument.Parse(jsonContent);
                }
                catch (Exception parseEx)
                {
                    return new CommandResult { Success = false, Result = $"解析secrets.json文件失败：{parseEx.Message}" };
                }
                
                // 使用字符串替换方式更新MiTestEntities，保持其他内容完全不变
                string updatedJsonContent = jsonContent;
                
                // 查找并替换MiTestEntities的值
                var regex = new System.Text.RegularExpressions.Regex(@"""MiTestEntities""\s*:\s*""([^""]*)""");
                string replacement = $"\"MiTestEntities\": \"{encryptedConnectionString}\"";
                updatedJsonContent = regex.Replace(updatedJsonContent, replacement);
                
                // 备份原文件
                string backupPath = secretsPath + ".backup." + DateTime.Now.ToString("yyyyMMddHHmmss");
                File.Copy(secretsPath, backupPath);
                
                // 写入更新后的内容
                File.WriteAllText(secretsPath, updatedJsonContent, Encoding.UTF8);
                
                return new CommandResult 
                { 
                    Success = true, 
                    Result = $"UserSecrets更新成功！\n原文件已备份至：{backupPath}\n加密的连接字符串已更新到MiTestEntities" 
                };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"更新UserSecrets时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteViewSecretsCommand()
        {
            try
            {
                // 构建UserSecrets路径
                string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string secretsPath = Path.Combine(userProfile, @"AppData\Roaming\Microsoft\UserSecrets\e67ad845-4b88-4662-9d66-34960dfb67d9\secrets.json");
                
                if (!File.Exists(secretsPath))
                {
                    return new CommandResult { Success = false, Result = $"找不到secrets.json文件：{secretsPath}" };
                }
                
                // 读取JSON文件内容
                string jsonContent;
                try
                {
                    jsonContent = File.ReadAllText(secretsPath, Encoding.UTF8);
                }
                catch (Exception readEx)
                {
                    return new CommandResult { Success = false, Result = $"读取secrets.json文件失败：{readEx.Message}" };
                }
                
                // 直接返回原始内容，不进行任何转义或格式化处理
                return new CommandResult 
                { 
                    Success = true, 
                    Result = jsonContent
                };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"查看UserSecrets时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteTestUserSecretsDatabaseCommand()
        {
            try
            {
                // 创建UserSecretsAESHelper实例
                UserSecretsAESHelper userSecretsHelper;
                try
                {
                    userSecretsHelper = new UserSecretsAESHelper();
                }
                catch (Exception helperEx)
                {
                    return new CommandResult { Success = false, Result = $"初始化UserSecrets配置失败：{helperEx.Message}" };
                }
                
                // 获取解密后的连接字符串
                string connectionString;
                try
                {
                    connectionString = userSecretsHelper.GetDecryptedConnectionString();
                }
                catch (Exception decryptEx)
                {
                    return new CommandResult { Success = false, Result = $"解密UserSecrets中的连接字符串失败：{decryptEx.Message}" };
                }
                
                if (string.IsNullOrEmpty(connectionString))
                {
                    return new CommandResult { Success = false, Result = "解密后的连接字符串为空" };
                }
                
                // 测试数据库连接
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    
                    // 执行一个简单的查询来验证连接
                    using (SqlCommand command = new SqlCommand("SELECT 1", connection))
                    {
                        object result = command.ExecuteScalar();
                        if (result != null && result.ToString() == "1")
                        {
                            return new CommandResult 
                            { 
                                Success = true, 
                                Result = $"UserSecrets数据库连接测试成功！\n服务器：{connection.DataSource}\n数据库：{connection.Database}\n" 
                            };
                        }
                        else
                        {
                            return new CommandResult { Success = false, Result = "UserSecrets数据库连接测试失败：查询返回异常结果" };
                        }
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                return new CommandResult { Success = false, Result = $"UserSecrets SQL Server连接错误：{sqlEx.Message}" };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"测试UserSecrets数据库连接时发生错误：{ex.Message}" };
            }
        }

        private static CommandResult ExecuteLongPingCommand(string command)
        {
            try
            {
                // 解析命令，提取IP地址
                string targetIp = "172.26.186.127"; // 默认IP
                if (!string.IsNullOrEmpty(command) && command.Contains("ping"))
                {
                    // 从命令中提取IP地址
                    var parts = command.Split(' ');
                    foreach (var part in parts)
                    {
                        if (System.Net.IPAddress.TryParse(part, out _))
                        {
                            targetIp = part;
                            break;
                        }
                    }
                }

                // 如果已经有ping进程在运行，先停止它
                if (_pingProcess != null && !_pingProcess.HasExited)
                {
                    StopLongPing();
                }

                // 启动新的ping进程
                StartLongPing(targetIp);

                return new CommandResult { Success = true, Result = $"开始长ping {targetIp}...\n\n[注意：ping进程已在后台运行，结果将实时显示在结果框中]" };
            }
            catch (Exception ex)
            {
                return new CommandResult { Success = false, Result = $"执行长ping时发生错误：{ex.Message}" };
            }
        }

        public static void StartLongPing(string targetIp)
        {
            try
            {
                _pingCancellationTokenSource = new CancellationTokenSource();
                _pingProcess = new Process();
                
                _pingProcess.StartInfo.FileName = "ping";
                _pingProcess.StartInfo.Arguments = $"-t {targetIp}"; // -t 参数表示持续ping
                _pingProcess.StartInfo.UseShellExecute = false;
                _pingProcess.StartInfo.RedirectStandardOutput = true;
                _pingProcess.StartInfo.RedirectStandardError = true;
                _pingProcess.StartInfo.CreateNoWindow = true;
                _pingProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                _pingProcess.StartInfo.StandardErrorEncoding = Encoding.UTF8;

                _pingProcess.Start();
                _pingProcess.BeginOutputReadLine();
                _pingProcess.BeginErrorReadLine();
            }
            catch (Exception ex)
            {
                throw new Exception($"启动长ping失败：{ex.Message}");
            }
        }

        public static void StopLongPing()
        {
            try
            {
                if (_pingProcess != null && !_pingProcess.HasExited)
                {
                    _pingProcess.Kill();
                    _pingProcess.WaitForExit(5000); // 等待最多5秒
                }
                
                _pingCancellationTokenSource?.Cancel();
                _pingCancellationTokenSource?.Dispose();
                _pingProcess?.Dispose();
                _pingProcess = null;
                _pingCancellationTokenSource = null;
            }
            catch (Exception ex)
            {
                throw new Exception($"停止长ping失败：{ex.Message}");
            }
        }

        public static bool IsLongPingRunning()
        {
            return _pingProcess != null && !_pingProcess.HasExited;
        }
    }
} 